// 文件路径: Server/src/main/java/com/hunterai/controller/UserController.java
package com.hunterai.controller;

import com.hunterai.dto.UserDTO;
import com.hunterai.dto.ProfileParams;
import com.hunterai.dto.ProfileDetail;
import com.hunterai.entity.User;
import com.hunterai.service.UserService;
import com.hunterai.security.JwtUtil;
import com.hunterai.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.multipart.MultipartFile;
import com.hunterai.dto.ReturnData;
import com.hunterai.util.FileStorageUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    @Autowired
    public UserController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @Value("${avatar.upload.dir}")
    private String avatarUploadDir;

    // 获取当前用户资料的API
    @GetMapping("/profile")
    public ReturnData<UserVO> getCurrentUserProfile(@RequestHeader("Authorization") String authorization) {
        // 提取token
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "未提供有效的认证信息");
        }
        
        String token = authorization.substring(7); // 去掉"Bearer "前缀
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的认证信息");
        }
        
        // 从token中提取用户ID
        Long userId = jwtUtil.extractUserId(token);
        
        // 获取用户信息
        Optional<UserDTO> userOptional = userService.findById(userId);
        if (userOptional.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        
        // 转换为VO对象并返回
        return ReturnData.success(convertToVO(userOptional.get()));
    }

    // 修改当前用户资料的API
    @PutMapping("/profile")
    public ReturnData<ProfileDetail> updateCurrentUserProfile(@RequestHeader("Authorization") String authorization,
                                                                 @RequestBody ProfileParams profileParams) {
        // 提取token
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "未提供有效的认证信息");
        }
        
        String token = authorization.substring(7); // 去掉"Bearer "前缀
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的认证信息");
        }
        
        // 从token中提取用户ID
        Long userId = jwtUtil.extractUserId(token);
        
        // 获取用户信息
        Optional<UserDTO> userOptional = userService.findById(userId);
        if (userOptional.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        
        UserDTO currentUser = userOptional.get();
        
        // 从数据库获取完整的用户实体
        Optional<User> userEntityOptional = userService.findUserEntityById(userId);
        if (userEntityOptional.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        
        User user = userEntityOptional.get();
        
        // 只更新允许修改的字段
        if (profileParams.getNickName() != null) {
            user.setNickName(profileParams.getNickName());
        }
        if (profileParams.getMobile() != null) {
            user.setMobile(profileParams.getMobile());
        }
        
        // 处理性别字段
        if (profileParams.getGender() != null && !profileParams.getGender().isEmpty()) {
            try {
                user.setGender(User.Gender.valueOf(profileParams.getGender().toUpperCase()));
            } catch (IllegalArgumentException e) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "无效的性别值");
            }
        }
        
        // 保存更新后的用户信息
        UserDTO updatedUser = userService.save(user);
        
        // 转换为ProfileDetail并返回
        return ReturnData.success(convertToProfileDetail(updatedUser));
    }

    @GetMapping("/list")
    public ResponseEntity<List<UserVO>> getAllUsers() {
        List<UserVO> users = userService.findAll().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        return ResponseEntity.ok(users);
    }

    @GetMapping("/{id}")
    public ResponseEntity<UserVO> getUserById(@PathVariable Long id) {
        return userService.findById(id)
                .map(this::convertToVO)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<UserVO> createUser(@RequestBody User user) {
        UserDTO savedUser = userService.save(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(convertToVO(savedUser));
    }

    @PutMapping("/{id}")
    public ResponseEntity<UserVO> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (!userService.findById(id).isPresent()) {
            return ResponseEntity.notFound().build();
        }
        user.setId(id);
        UserDTO updatedUser = userService.save(user);
        return ResponseEntity.ok(convertToVO(updatedUser));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        if (!userService.findById(id).isPresent()) {
            return ResponseEntity.notFound().build();
        }
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    private UserVO convertToVO(UserDTO dto) {
        UserVO vo = new UserVO();
        vo.setId(dto.getId());
        vo.setUserName(dto.getUserName());
        vo.setEmail(dto.getEmail());
        vo.setCreatedAt(dto.getCreatedAt());
        vo.setLastLogin(dto.getLastLogin());
        vo.setAvatar(dto.getAvatar());
        vo.setNickName(dto.getNickName());
        vo.setGender(dto.getGender());
        vo.setMobile(dto.getMobile());
        // 如果需要，可以在这里添加角色等其他信息
        return vo;
    }

    private ProfileDetail convertToProfileDetail(UserDTO dto) {
        ProfileDetail detail = new ProfileDetail();
        detail.setId(dto.getId());
        detail.setUserName(dto.getUserName());
        detail.setEmail(dto.getEmail());
        detail.setAvatar(dto.getAvatar());
        detail.setNickName(dto.getNickName());
        detail.setGender(dto.getGender());
        detail.setMobile(dto.getMobile());
        detail.setCreateAt(dto.getCreatedAt());
        detail.setLastLogin(dto.getLastLogin());
        return detail;
    }

    // 修改用户头像API
    @PostMapping("/avatar")
    public ReturnData<UserVO> updateAvatar(@RequestHeader("Authorization") String authorization,
                                           @RequestParam("file") MultipartFile file) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "未提供有效的认证信息");
        }
        String token = authorization.substring(7);
        if (!jwtUtil.validateToken(token)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "无效的认证信息");
        }
        Long userId = jwtUtil.extractUserId(token);
    
        // 直接查User实体
        Optional<User> userOpt = userService.findUserEntityById(userId);
        if (userOpt.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        User user = userOpt.get();
    
        // 文件存储
        String uploadDir = avatarUploadDir; // 绝对路径
        String avatarUrl;
        try {
            avatarUrl = FileStorageUtil.saveAvatar(file, uploadDir);
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "头像上传失败");
        }
    
        // 只更新avatar字段
        user.setAvatar(avatarUrl);
        UserDTO updated = userService.save(user);
    
        return ReturnData.success(convertToVO(updated));
    }

    /**
     * 头像图片访问接口
     */
    @GetMapping("/avatar/{filename}")
    public ResponseEntity<Resource> getAvatar(@PathVariable String filename) {
    
        try {
            // 你的avatar物理存储目录（建议用配置注入）
            String avatarDir = avatarUploadDir;
            Path filePath = Paths.get(avatarDir).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }
            // 自动识别图片类型
            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}